// 动态路由配置
// 根据菜单权限动态生成路由

// 路由组件映射表
const routeComponents = {
  // 系统管理
  'UserManagement': () => import('../views/UserManagement.vue'),
  'RoleManagement': () => import('../views/RoleManagement.vue'),
  'MenuManagement': () => import('../views/MenuManagement.vue'),
  'PermissionManagement': () => import('../views/PermissionManagement.vue'),
  'OperationLogManagement': () => import('../views/OperationLogManagement.vue'),
  
  // 通知管理
  'NoticeManagement': () => import('../views/NoticeManagement.vue'),
  'NoticeView': () => import('../views/NoticeView.vue'),
  
  // 充值相关
  'Recharge': () => import('../views/Recharge.vue'),
  'RechargeRecord': () => import('../views/RechargeRecord.vue'),
  'RechargeManagement': () => import('../views/admin/RechargeManagement.vue'),
  
  // 预约相关
  'Appointment': () => import('../views/Appointment.vue'),
  'MyAppointments': () => import('../views/MyAppointments.vue'),
  'AppointmentManagement': () => import('../views/AppointmentManagement.vue'),
  'AdminAppointmentRecords': () => import('../views/AdminAppointmentRecords.vue'),

  // 业务管理（店长端）
  'views/WorkSchedule': () => import('../views/WorkSchedule.vue'),
  'views/StoreAppointments': () => import('../views/StoreAppointments.vue'),
  'views/StoreProductManagement': () => import('../views/StoreProductManagement.vue'),
  
  // 其他业务模块
  'SupplyProductManagement': () => import('../views/SupplyProductManagement.vue'),
  'StockRecordManagement': () => import('../views/StockRecordManagement.vue'),
  'views/CurrentInventory': () => import('../views/CurrentInventory.vue'),
  'store/HaircutPackageManagement': () => import('../views/store/HaircutPackageManagement.vue'),
  'HaircutPackageManagement': () => import('../views/store/HaircutPackageManagement.vue'),
  'WorkSchedule': () => import('../views/WorkSchedule.vue'),
  'SystemConfig': () => import('../views/extension/SystemConfig.vue'),
  
  // 购买相关
  'ProductPurchase': () => import('../views/ProductPurchase.vue'),
  'ProductDetail': () => import('../views/ProductDetail.vue'),
  'MyPurchaseRecords': () => import('../views/MyPurchaseRecords.vue'),
  'PurchaseRecordManagement': () => import('../views/PurchaseRecordManagement.vue'),
  
  // 管理员功能
  'AdminStockRecords': () => import('../views/AdminStockRecords.vue'),
  'AdminInventoryManagement': () => import('../views/AdminInventoryManagement.vue'),
  
  // 店长报表
  'StoreReports': () => import('../views/store/StoreReports.vue'),
  'SimpleTest': () => import('../views/SimpleTest.vue'),
  
  // 管理员报表
  'AdminReports': () => import('../views/admin/AdminReports.vue'),
  
  // 个人中心
  'Profile': () => import('../views/Profile.vue')
}

/**
 * 根据菜单数据生成动态路由
 * @param {Array} menus 用户菜单数据
 * @returns {Array} 动态路由配置
 */
export function generateDynamicRoutes(menus) {
  const routes = []
  console.log('开始生成动态路由，菜单数据:', menus)

  // 递归处理菜单数据
  function processMenus(menuList, parentPath = '') {
    menuList.forEach(menu => {
      console.log(`处理菜单项:`, {
        menuName: menu.menuName,
        menuType: menu.menuType,
        path: menu.path,
        component: menu.component
      })

      // 只处理菜单类型，忽略目录和按钮
      if (menu.menuType === 'MENU' && menu.path && menu.component) {
        const routeConfig = {
          path: menu.path,
          name: menu.component, // 使用组件名作为路由名称
          component: routeComponents[menu.component],
          meta: {
            title: menu.menuName,
            requiresMenu: true,
            menuPath: menu.path,
            menuId: menu.id,
            menuCode: menu.menuCode
          }
        }

        // 确保组件存在
        if (routeComponents[menu.component]) {
          routes.push(routeConfig)
          console.log(`✓ 添加路由: ${menu.path} -> ${menu.component}`)
        } else {
          console.warn(`✗ 组件 ${menu.component} 未找到，跳过路由 ${menu.path}`)
          console.warn('可用组件列表:', Object.keys(routeComponents))
        }
      } else {
        console.log(`跳过非菜单项: ${menu.menuName} (类型: ${menu.menuType})`)
      }

      // 递归处理子菜单
      if (menu.children && menu.children.length > 0) {
        processMenus(menu.children, menu.path)
      }
    })
  }

  processMenus(menus)
  console.log(`动态路由生成完成，共生成 ${routes.length} 个路由:`, routes.map(r => ({ path: r.path, name: r.name })))
  return routes
}

/**
 * 检查路由是否在用户菜单中
 * @param {String} routePath 路由路径
 * @param {Array} menus 用户菜单数据
 * @returns {Boolean} 是否有权限访问
 */
export function hasRoutePermission(routePath, menus) {
  console.log(`检查路由权限: ${routePath}`)

  if (!routePath || !menus || menus.length === 0) {
    console.log('权限检查失败: 路径为空或菜单数据为空')
    return false
  }

  function checkMenuTree(menuList, targetPath) {
    for (const menu of menuList) {
      // 检查当前菜单
      if (menu.path === targetPath) {
        console.log(`✓ 找到匹配路径: ${targetPath} 在菜单 ${menu.menuName} 中`)
        return true
      }

      // 检查子菜单
      if (menu.children && menu.children.length > 0) {
        if (checkMenuTree(menu.children, targetPath)) {
          return true
        }
      }
    }
    return false
  }

  const hasPermission = checkMenuTree(menus, routePath)
  console.log(`路由权限检查结果: ${routePath} -> ${hasPermission}`)

  if (!hasPermission) {
    console.log('可用路径列表:', getAvailableRoutePaths(menus))
  }

  return hasPermission
}

/**
 * 获取所有可用的路由路径
 * @param {Array} menus 用户菜单数据
 * @returns {Array} 路由路径列表
 */
export function getAvailableRoutePaths(menus) {
  const paths = []
  
  function extractPaths(menuList) {
    menuList.forEach(menu => {
      if (menu.menuType === 'MENU' && menu.path) {
        paths.push(menu.path)
      }
      
      if (menu.children && menu.children.length > 0) {
        extractPaths(menu.children)
      }
    })
  }
  
  extractPaths(menus)
  return paths
} 